################################
### SRT structures & classes ###
################################

class srt_event:

	time_start = "00:00:00.000"
	time_end = "00:00:00.000"
	margin_left = -1
	margin_right = -1
	margin_top = -1
	margin_bottom = -1
	text = []

class srt:

	events = []

	def merge_event(self, event):
		# FIXME: each insert needs to be verified, if the event timespan overlaps with existing timespans
		# if yes a resampling is required
		overlap_count = 0
		visible_time = 0
		overlap_time = 0
		overlap_mode = ""
		ins_t1 = timecode_to_milli(event.time_start)
		ins_t2 = timecode_to_milli(event.time_end)
		for evt in self.events:
			ex_t1 = timecode_to_milli(evt.time_start)
			ex_t2 = timecode_to_milli(evt.time_end)
			if ((ins_t1 < ex_t2)and (ins_t2 > ex_t1)):
				overlap_count = overlap_count + 1
				# new timespan lies inside of existing timespan
				if ((ins_t1 >= ex_t1) and (ins_t2 <= ex_t2)):
					overlap_mode = "Inside"
					visible_time = ins_t2-ins_t1
					overlap_time = ex_t1-ins_t1 + ins_t2-ex_t2
					if (warnings):
						#print(overlap_mode)
						print("        [" + evt.time_start + "  <  " + str(visible_time).zfill(5) + "  >  " + evt.time_end + "]")
				# new timespan wraps the existing timespan
				if ((ins_t1 < ex_t1) and (ins_t2 > ex_t2)):
					overlap_mode = "Wrap"
					visible_time = ex_t2-ex_t1
					overlap_time = ex_t1-ins_t1 + ins_t2-ex_t2
					if (warnings):
						#print(overlap_mode)
						print("  " + str(ex_t1-ins_t1).zfill(5) + " - [" + evt.time_start + " < " + str(visible_time).zfill(5) + " > " + evt.time_end + "] - " + str(ins_t2-ex_t2).zfill(5))
				# new timespan obverlap to the left of the existing timespan
				if ((ins_t1 < ex_t1) and (ins_t2 <= ex_t2)):
					overlap_mode = "Left"
					visible_time = ins_t2-ex_t1
					overlap_time = ex_t1-ins_t1 + ins_t2-ex_t2
					if (warnings):
						#print(overlap_mode)
						print("  " + str(ex_t1-ins_t1).zfill(5) + " - [" + evt.time_start + " < " + str(visible_time).zfill(5) + "  >  " + evt.time_end + "]")
				# new timespan obverlap to the right of the existing timespan
				if ((ins_t1 >= ex_t1) and (ins_t2 > ex_t2)):
					overlap_mode = "Right"
					visible_time = ex_t2-ins_t1
					overlap_time = ex_t1-ins_t1 + ins_t2-ex_t2
					if (warnings):
						#print(overlap_mode)
						print("        [" + evt.time_start + "  <  " + str(visible_time).zfill(5) + " > " + evt.time_end + "] - " + str(ins_t2-ex_t2).zfill(5))
				#if (warnings):
				#	for line in evt.text:
				#		print("    > " + line)
		if (overlap_count > 0):
			if (warnings):
				print("        [" + event.time_start + "  <  " + str(ins_t2-ins_t1).zfill(5) + "  >  " + event.time_end + "]" )
				#for line in event.text:
				#	print("    + " + line)
				print("")
		self.events.append(event)

	def load(self, filename):
		print("Loading: '" + filename + "'")
		filestream = open(filename, 'r')
		for line in file:
			event = srt_event()
			event.text = [] # NOTE: event.text has value from previous loop iteration, so we need to reset it
			# skip id
			line = strip_line(filestream.next())
			# read timespan / position
			event.time_start = line[0:12].replace(",", ".")
			event.time_end = line[17:29].replace(",", ".")
			positions = line[30:].split(" ")
			if (len(positions) == 4):
				for pos in positions:
					if (pos[0:3].upper() == "X1:"):
						event.margin_left = int(pos[3:])
					if (pos[0:3].upper() == "X2:"):
						event.margin_right = int(pos[3:])
					if (pos[0:3].upper() == "Y1:"):
						event.margin_top = int(pos[3:])
					if (pos[0:3].upper() == "Y2:"):
						event.margin_bottom = int(pos[3:])
			line = strip_line(filestream.next())
			# read text
			while (line):
				event.text.append(line)
				try:
					line = strip_line(filestream.next())
				except StopIteration:
					break
			self.events.append(event)
		filestream.close()

	def save(self, filename):
		advanced = 0
		print("Saving: '" + filename + "'")
		filestream = open(filename, 'w')
		event_id = 0
		for event in self.events:
			if (len(event.text) > 0):
				event_id = event_id+1
				filestream.write(str(event_id) + newline)
				filestream.write(event.time_start.replace(".", ",") + " --> " + event.time_end.replace(".", ","))
				if (advanced) and (event.margin_left > -1) and (event.margin_right > -1) and (event.margin_top > -1) and (event.margin_bottom > -1):
					filestream.write(" X1:" + str(event.margin_left).zfill(3))
					filestream.write(" X2:" + str(event.margin_right).zfill(3))
					filestream.write(" Y1:" + str(event.margin_top).zfill(3))
					filestream.write(" Y2:" + str(event.margin_bottom).zfill(3))
				filestream.write(newline)
				for line in event.text:
					if (not(advanced)):
						line = re.sub(r"\{\\.*?\}", "", line) # override blocks {\*}
						line = re.sub(r"</?(b|i|u|s|font.*?)>", "", line) # remove common tags
					if (line):
						filestream.write(line + newline)
				filestream.write(newline)
		filestream.close()
